<template>
  <div class="app-container">
    <el-row :gutter="20" class="div-height-left">
      <el-col v-if="userInfo.userId === '1'" :span="4" class="div-height-left">
        <sys-org-tree @treeClick="treeClick"/>
      </el-col>
      <el-col :span="userInfo.userId === '1' ? 20 : 24" :xs="24">
        <div class="search-container">
          <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams"
                   label-width="100px">
            <el-form-item label="类型" prop="dictType">
              <el-select v-model="queryParams.dictType" class="width-120" clearable placeholder="请选择类型"
                         @change="typeChange">
                <el-option v-for="(dict, index ) in sysBaseDictTypeList" :key="dict.dictType"
                           :label="dict.baseDictName" :value="dict.dictType"/>
              </el-select>
            </el-form-item>
            <el-form-item label="门诊住院标识" prop="outpOrInp">
              <el-select v-model="queryParams.outpOrInp" clearable placeholder="请选择门诊住院标识"
                         style="width: 140px">
                <el-option v-for="dict in dictDataMap['clinic_or_visit']" :key="dict.dictValue"
                           :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
            </el-form-item>
          </el-form>
        </div>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPerm="['base:administrationDict:insert']" :disabled="!queryParams.orgId" plain
                       type="warning" @click="handleInsert">
              <template #icon>
                <i-ep-bottom/>
              </template>
              插入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPerm="['system:sysOrgDict:add']" plain type="primary" @click="handleAdd">
              <template #icon>
                <i-ep-plus/>
              </template>
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPerm="['system:sysOrgDict:edit']" :disabled="single" plain type="success"
                       @click="handleUpdate">
              <template #icon>
                <i-ep-edit/>
              </template>
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPerm="['system:sysOrgDict:remove']" :disabled="multiple" plain type="danger"
                       @click="handleDelete">
              <template #icon>
                <i-ep-delete/>
              </template>
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPerm="['system:sysOrgDict:export']" plain type="warning" @click="handleExport">
              <template #icon>
                <i-ep-download/>
              </template>
              导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button plain type="danger"
                       @click="handleRefreshCache">
              <template #icon>
                <i-ep-refresh/>
              </template>
              刷新缓存
            </el-button>
          </el-col>
        </el-row>

        <el-table v-adaptive :border="true" :data="sysOrgDictList" :header-cell-style="$headerCellStyle"
                  :stripe="true" highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column :align="'center'" type="selection" width="55"/>
          <el-table-column :align="'center'" label="字典标签" prop="dictLabel">
            <template #default="scope">
                            <span v-if="scope.row.listClass == '' || scope.row.listClass == 'default'">{{
                                scope.row.dictLabel
                              }}</span>
              <el-tag v-else :type="scope.row.listClass == 'primary' ? '' : scope.row.listClass">
                {{ scope.row.dictLabel }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="类型" prop="dictType"/>
          <el-table-column :align="'center'" label="类型" prop="dictType"/>
          <el-table-column :align="'center'" label="值" prop="dictValue"/>
          <el-table-column :align="'center'" label="排序" prop="dictSort"/>
          <el-table-column :align="'center'" label="门诊住院标识" prop="outpOrInp">
            <template #default="scope">
              <dict-data-tag :options="dictDataMap['clinic_or_visit']" :value="scope.row.outpOrInp"/>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="是否已对照" prop="clinicId"
                           width="100">
            <template #default="scope">
              <el-tag :type="scope.row.clinicItemId != null ? 'success' : 'warning'">
                {{ scope.row.clinicItemId != null ? '已对照' : '未对照' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="备注信息" prop="remarks"/>
          <el-table-column :align="'center'" label="医保值" prop="medicalValue"/>
          <el-table-column :align="'center'" label="医保标签" prop="medicalLabel"/>
          <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作" width="280">
            <template #default="scope">
              <el-button v-hasPerm="['base:clinicItemDict:addControl']" type="success"
                         @click="addControl(scope.row)">
                <template #icon>
                  <i-ep-edit/>
                </template>
                添加对照
              </el-button>
              <el-button v-hasPerm="['system:sysOrgDict:edit']" type="success"
                         @click="handleUpdate(scope.row)">
                <template #icon>
                  <i-ep-edit/>
                </template>
                修改
              </el-button>
              <el-button v-hasPerm="['system:sysOrgDict:remove']" type="danger"
                         @click="handleDelete(scope.row)">
                <template #icon>
                  <i-ep-delete/>
                </template>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                    :total="total" @pagination="getList"/>
      </el-col>
    </el-row>
    <!-- 添加或修改机构数据字典对话框 diagmove -->
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标签" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入标签"/>
        </el-form-item>
        <el-form-item label="类型" prop="dictType">
          <el-input v-model="form.dictType" disabled/>
        </el-form-item>
        <el-form-item label="值" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入值"/>
        </el-form-item>
        <el-form-item label="排序" prop="dictSort">
          <el-input v-model="form.dictSort" placeholder="请输入排序"/>
        </el-form-item>
        <el-form-item label="门诊住院标识" prop="outpOrInp">
          <el-select v-model="form.outpOrInp" placeholder="请选择门诊住院标识">
            <el-option v-for="dict in dictDataMap['clinic_or_visit']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="回显样式" prop="listClass">
          <el-select v-model="form.listClass">
            <el-option v-for="item in listClassOptions" :key="item.value"
                       :label="item.label + '(' + item.value + ')'" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="样式属性" prop="cssClass">
          <el-input v-model="form.cssClass" placeholder="请输入样式属性"/>
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注信息"/>
        </el-form-item>
        <el-form-item label="医保值" prop="medicalValue">
          <el-input v-model="form.medicalValue" placeholder="请输入医保值"/>
        </el-form-item>
        <el-form-item label="医保标签" prop="medicalLabel">
          <el-input v-model="form.medicalLabel" placeholder="请输入医保标签"/>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
      </template>
    </el-dialog>
    <dict-insert-dialog ref="dictInsertDialogRef" @refreshParentList="refreshParentList"
                        @submit-form="insertSubmit"/>
    <control-sys-org-dict-dialog ref="controlSysOrgDictDialogRef" @selectClinicList="getList"
                                 @save-sys-org-dict-control="saveSysOrgDictControl"/>
  </div>
</template>
<script lang="ts">
export default {
  name: "SysOrgDict"
}
</script>

<script lang="ts" setup>
import {
  addSysOrgDict,
  delSysOrgDict,
  getSysOrgDict,
  selectPageSysOrgDict,
  updateSysOrgDict,
  saveBatchOrgDictInData,
  updateSysOrgDictToClinic,
  refreshCache
} from "@/api/system/sysOrgDict";
import {useUserStoreHook} from "@/store/modules/user"
import {useDictStoreHook} from "@/store/modules/dict";
import {listSysBaseDictType} from "@/api/system/sysBaseDictType";
import dictInsertDialog from "@/views/base/administrationDict/dictInsertDialog.vue"
import controlSysOrgDictDialog from "./controlSysOrgDictDialog.vue"

const useUserStore = useUserStoreHook();
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('clinic_or_visit'))
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo

const controlSysOrgDictDialogRef = ref()

const {proxy} = getCurrentInstance() as any;
const dictInsertDialogRef = ref()
const formRef = ref();
const queryParamsRef = ref()
const sysOrgDictList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const sysBaseDictTypeList = ref<any>({})

const form = ref(<any>{
  dictLabel: undefined,
  dictType: undefined,
  dictValue: undefined,
  outpOrInp: "",
  remarks: ""
})
const queryParams = ref(<any>{
  pageNum: 1,
  pageSize: 10,
  dictLabel: undefined,
  dictType: undefined,
  dictValue: undefined,
  outpOrInp: "",
  remarks: "",
  orgId: ""
})
const dictName = ref("")
// 数据标签回显样式
const listClassOptions = ref([
  {
    value: "default",
    label: "默认"
  },
  {
    value: "primary",
    label: "主要"
  },
  {
    value: "success",
    label: "成功"
  },
  {
    value: "info",
    label: "信息"
  },
  {
    value: "warning",
    label: "警告"
  },
  {
    value: "danger",
    label: "危险"
  }
])
const rules = ref(<any>{
  label: [
    {
      required: true, message: "标签不能为空", trigger: "blur"
    }
  ],
  dictType: [
    {
      required: true, message: "类型不能为空", trigger: "change"
    }
  ],
  value: [
    {
      required: true, message: "值不能为空", trigger: "blur"
    }
  ],
  sort: [
    {
      required: true, message: "排序不能为空", trigger: "blur"
    }
  ],
})
getBaseList()
if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId
  // getList()
}

function saveSysOrgDictControl(form) {
  updateSysOrgDictToClinic(form.value).then(_response => {
    ElMessage.success("对照成功");
    controlSysOrgDictDialogRef.value.cancel()
  })
}

function addControl(row) {
  row.orgId = queryParams.value.orgId
  nextTick(() => {
    controlSysOrgDictDialogRef.value.addControlDialogShow(row)
  })
}

/** 左侧科室树节点点击事件 */
function treeClick(obj) {
  queryParams.value.orgId = obj.id
  getList()
}

/** 查询字典类型列表 */
function getBaseList() {
  listSysBaseDictType({"status": 0}).then((response: any) => {
    sysBaseDictTypeList.value = response.data;
  });
}

/** 查询机构数据字典列表 */
function getList() {
  if (!queryParams.value.orgId) {
    return ElMessage.error(proxy.$OrgIdIsEmpty)
  }
  selectPageSysOrgDict(queryParams.value).then((response: any) => {
    sysOrgDictList.value = response.rows;
    total.value = response.total;
  });
}

/** 字典插入 */
function handleInsert() {
  if (!queryParams.value.orgId) {
    return ElMessage.error(proxy.$OrgIdIsEmpty)
  }
  if (!queryParams.value.dictType) {
    return ElMessage.error("请选择类型后再操作。")
  }
  let obj = {
    'title': '机构字典插入',
    'dictType': queryParams.value.dictType,
    'dictName': dictName.value,
    'orgId': queryParams.value.orgId,
    'isType': "2"
  }
  dictInsertDialogRef.value.showDictInsertDialog(obj)
}

/** 插入页面返回查询 */
function refreshParentList() {
  handleQuery()
}

function typeChange() {
  const findIndex = sysBaseDictTypeList.value.findIndex((item: any) => {
    return item.dictType === queryParams.value.dictType
  });
  if (findIndex > -1) {
    dictName.value = sysBaseDictTypeList.value[findIndex].baseDictName
  }
  getList()
  // handleInsert()
}

function insertSubmit(data) {
  saveBatchOrgDictInData(data).then((res: any) => {
    ElMessage.success("插入成功")
    cancel()
    typeChange()
  })
}

// 取消按钮
function cancel() {
  open.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  // proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orgDictId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  if (!queryParams.value.orgId) {
    return ElMessage.error(proxy.$OrgIdIsEmpty)
  }
  open.value = true;
  title.value = "添加机构数据字典";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  open.value = true;
  const _orgDictId = row.orgDictId || ids.value
  debugger
  getSysOrgDict(_orgDictId).then((response: any) => {
    form.value = response.data;
    title.value = "修改机构数据字典";
  });
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.orgDictId != null) {
        updateSysOrgDict(form.value).then((response: any) => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addSysOrgDict(form.value).then((response: any) => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const orgDictIds = row.orgDictId || ids.value;
  ElMessageBox.confirm('是否确认删除机构数据字典数据？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delSysOrgDict(orgDictIds).then(() => {
      getList();
      ElMessage.success("删除成功");
    })
  }).catch(() => {
  })
}

/** 刷新缓存按钮操作 */
function handleRefreshCache() {
  refreshCache(queryParams.value.orgId).then(() => {
    ElMessage.success("刷新成功");
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/sysOrgDict/export', {
    ...queryParams.value
  }, `sysOrgDict_${new Date().getTime()}.xlsx`)
}

getList();
</script>
